package com.cjy.common.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.base.common.GlobaConstants;

/**
 * User: jay.zhoujingjie Date: 14-1-15 Time: 下午5:56
 */
public class LoginValidateFilter implements Filter {
	// 登录action URL
	private List<String> excludeURI;
	private String loginURI;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		String config = filterConfig.getInitParameter("excludeURI");
		config = (config == null) ? "" : config;
		excludeURI = Arrays.asList(config.split(","));
		loginURI = filterConfig.getInitParameter("loginURI");
		loginURI = (loginURI == null) ? "" : loginURI;
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		if (request.getSession().getAttribute(GlobaConstants.LOGIN_USER) == null) {
			String uri = request.getRequestURI();
			String ctx = request.getContextPath();
			String qs = request.getQueryString();
			qs = qs == null ? "" : qs;
			uri = uri.replace(ctx, "");
			uri = uri.replace(qs, "");
			if (uri.endsWith("?")) {
				uri = uri.substring(0, uri.length() - 1);
			}
			if ("".equals(uri) || "/".equals(uri) || excludeURI.contains(uri)) {
				chain.doFilter(request, response);
			} else {
				// 未登录则登录
				request.getRequestDispatcher(loginURI).forward(request,
						response);
			}
		} else {
			chain.doFilter(request, response);
		}
	}

	@Override
	public void destroy() {
	}
}
